package hello.dao;

import javax.persistence.EmbeddedId;
import javax.persistence.Id;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class S {

    static String d = "package hello.dao;\n" +
            "import hello.pojo.%s;\n" +
            "import org.springframework.data.jpa.repository.JpaRepository;\n" +
            "import org.springframework.data.rest.core.annotation.RepositoryRestResource;\n" +
            "\n" +
            "@RepositoryRestResource(collectionResourceRel = \"%s\", path = \"%s\")\n" +
            "public interface %sRepository extends JpaRepository<%s, %s> {\n" +

            "}";

    private static final String root = System.getProperty("user.dir") + "/src/main/java/";

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        String p = "hello.pojo.";

        Map<Class<?>, Object> map = new HashMap<Class<?>, Object>() {
            {
                put(int.class, 0);
                put(long.class, 0l);
                put(short.class, (short) 0);
                put(double.class, 0d);
                put(byte.class, (byte) 0);
                put(boolean.class, false);
            }
        };


        String[] f = new File(root + "hello/pojo").list();
        for (String s1 : f) {
            System.out.println(s1);
            Class<?> c = Class.forName(p + s1.split("\\.")[0]);
            String n = c.getSimpleName();

            Class<?> c1 = h(c);
           /* if (c1.isPrimitive()) {
                System.out.println(c1);
               Object r= map.get(c);
                System.out.println(r);
               if (r==null)continue;
                c1=r.getClass();
            }*/
           if (c1==null)continue;
            String ff = c1.getSimpleName();
            ff = ff.substring(0, 1).toUpperCase() + ff.substring(1);
            FileWriter e = new FileWriter(root + "hello/dao/" + n + "Repository.java");
            e.write(String.format(d, n, n, n, n, n, ff));
            e.flush();
            e.close();
            System.out.println();
        }

    }

    private static Class<?> h(Class<?> c) {
        for (Method m : c.getMethods()) {
            Annotation[] d = m.getDeclaredAnnotations();
            for (Annotation a : d) {
                Class<?> cc=a.annotationType();
                if ( cc== Id.class||cc== EmbeddedId.class) {
                    String s2 = m.getName();
                    s2 = s2.substring(0, 1).toLowerCase() + s2.substring(1);
                    return m.getReturnType();

                }
            }

        }


        return null;
    }
}
